﻿
namespace MuddyBoots.Greenlight.QC.Common.Patterns.Behaviour.Mediator
{
    /// <summary>
    /// Casting and validation of mediator arguments
    /// </summary>
    /// <typeparam name="T">The type of argument</typeparam>
    public static class MediatorHelper<T> where T : class
    {
        /// <summary>
        /// Gets the argument.
        /// </summary>
        /// <param name="obj">The object.</param>
        /// <returns>The argument cast to its sub type</returns>
        public static T GetArgument(object obj)
        {
            if (obj == null)
            {
                throw new NullMediatorArgumentException("Mediator argument was null");
            }

            var argument = obj as T;

            if (argument == null)
            {
                throw new NullMediatorArgumentException("Could not convert mediator argument to its expected type");
            }

            return argument;
        }

        /// <summary>
        /// Tries the get argument.
        /// </summary>
        /// <param name="obj">The object.</param>
        /// <returns>An instance of type T or null</returns>
        public static T TryGetArgument(object obj)
        {
            if (obj == null)
            {
                return null;
            }

            T argument;
            try
            {
                argument = obj as T;
            }
            catch
            {
                return null;
            }

            if (argument == null)
            {
                return null;
            }

            return argument;
        }
    }
}
